﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace HotelATM_Guru
{
    [ComVisible(true)]
    public partial class frmMain : Form
    {
        bool mousePressed=false;
        Point diff = new Point(0, 0);
        List<CWeather> lstWea;
        private int current = 0;
        string path;
        string focuszoom = "12";
        string lathotel = "";
        string lnghotel = "";
        
        public frmMain()
        {
            InitializeComponent();
            this.path = AppDomain.CurrentDomain.BaseDirectory;
            this.InitializeWebBrowser();
        }
        private void InitializeWebBrowser()
        {
            webBrowser_Map.ObjectForScripting = this;
        }

        #region Khu vực khởi tạo
        public void InitControls()
        {
            webBrowser_Map.Url = new Uri(Path.Combine(path, @"Web\Map.htm"));

            lstWea = new List<CWeather>();
            try
            {
                lstWea = CGetData.GetDataWeather();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void InitComboBox()
        {
            cmbATM.DataSource = XML.Bank_GetAllBank();
            cmbHotel.DataSource = XML.Hotel_GetAllDistrict();
        }
        #endregion

        #region Weather
        private void ShowWeather()
        {
            picWeather.Image = Image.FromFile(lstWea[current].iconUrl);
            if (lstWea[current].Date == "current")
                lblDate.Text = "Current";
            else
                lblDate.Text = DateTime.Parse(lstWea[current].Date).ToString("dd-MMMM");
            lblTempC.Text = lstWea[current].temp_C + " \x00B0C";
            lblTempF.Text = lstWea[current].temp_F + " \x00B0F";
            lblDesc.Text = lstWea[current].weatherDesc;
        }
        #endregion

        #region Hien thi thong tin marker
        public void GetLatLngHotel(string _lat, string _lng)
        {
            lathotel = _lat; 
            lnghotel = _lng;
        }
        public void DisplayInfoHotel(string name, string add, string detail, string image)
        {
            string displayInfo = string.Format("{0}{1}Địa chỉ: {2}{3}{4}", name, Environment.NewLine, add, Environment.NewLine, detail);
            lblInfo.Text = displayInfo;
            pBHotelAvatar.ImageLocation = @"Misc\" + image;
            button1.Visible = true;
        }

        public List<CPosATM> GetPostATMaroundHotel()
        {
            //if (lathotel == "" || lnghotel == "")
            //    return;
            double lat_hotel = double.Parse(lathotel);
            double lng_hotel = double.Parse(lnghotel);
            List<CPosATM> lstATM = XML.Bank_GetAllATM();
            Dictionary<int, double> dict = new Dictionary<int, double>();
            int i = 0;
            foreach (CPosATM atm in lstATM)
            {
                double _lat = double.Parse(atm.lat);
                double _lng = double.Parse(atm.lng);
                double temp = Math.Sqrt(Math.Pow(_lat - lat_hotel, 2) + Math.Pow(_lng - lng_hotel, 2));
                dict.Add(i, temp);
                i++;
            }
            var dictsort = (from entry in dict orderby entry.Value ascending select entry);
            int j = 0;
            List<CPosATM> lstketqua = new List<CPosATM>();
            foreach (KeyValuePair<int, double> key in dictsort)
            {
                if (j == 20)
                {
                    break;
                }
                lstketqua.Add(lstATM[key.Key]);
                j++;
            }
            return lstketqua;
        }
        public void DisplayInfoATM(string name, string add, string detail, string image)
        {
            string displayInfo = string.Format("{0}{1}Địa chỉ: {2}{3}Thời gian hoạt động: {4}", name, Environment.NewLine, add, Environment.NewLine, detail);
            lblInfo.Text = displayInfo;
            pBHotelAvatar.ImageLocation = @"Misc\" + image;
        }
        #endregion
        
        private void Form1_Load(object sender, EventArgs e)
        {
            BitmapRegion.CreateControlRegion(this, Properties.Resources.bg);
            System.Drawing.Drawing2D.GraphicsPath gp = BitmapRegion.CalculateControlGraphicsPath(Properties.Resources.maparea);
            webBrowser_Map.Region = new Region(gp);

            lblTime.Text = DateTime.Now.ToLongTimeString();
            InitControls();
            ShowWeather();
            //XML.WriteATMToXML(CGetData.GetPosATMDongABank(), CGetData.GetPosATMACBBank(), CGetData.GetPosATMVietcomBank());
            List<CPosATM> lst = XML.Bank_GetAllATM();
            InitComboBox();
        }
        #region Xu ly cac su kien keo re form
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mousePressed = true;
                Point p = new Point(e.X, e.Y);
                p = PointToScreen(p);
                diff.X = p.X - DesktopLocation.X;
                diff.Y = p.Y - DesktopLocation.Y;
            }
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (mousePressed && (e.Button & MouseButtons.Left) != 0)
            {
                Point p = new Point(e.X, e.Y);
                p = PointToScreen(p);
                p.X -= diff.X;
                p.Y -= diff.Y;
                DesktopLocation = p;
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            mousePressed = false;
        }
        #endregion

        #region Sự kiện panel map
        private void pbBtnClose_MouseEnter(object sender, EventArgs e)
        {
           pbBtnClose.Image = Properties.Resources.btnExit_2;
        }

        private void pbBtnClose_MouseLeave(object sender, EventArgs e)
        {
            pbBtnClose.Image = Properties.Resources.btnExit;
        }

        private void pbBtnClose_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
        #endregion

        #region "Sự kiện panel weather"
        private void btnLeft_Click(object sender, EventArgs e)
        {
            if (current > 0)
            {
                current--;
                ShowWeather();
            }
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            if (current < 2)
            {
                current++;
                ShowWeather();
            }
        }
        private void tmrTime_Tick(object sender, EventArgs e)
        {
            lblTime.Text = DateTime.Now.ToLongTimeString();
        }
        #endregion

        #region "Sự kiện panel search"
        private void rBHotel_CheckedChanged(object sender, EventArgs e)
        {
            bool b = rBHotel.Checked;
            cmbATM.Visible = !b;
            txtAddress.Visible = !b;
            cmbHotel.Visible = b; 
            cmbHotelMethod.Visible = b;
            cmbHotelMethod.SelectedIndex = 0;
            //cmbHotelMethod_SelectedIndexChanged(sender, e);
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            ClearMarker();
            button1.Visible = false;
            if (rBHotel.Checked)
            {
                List<CPosHotel> lstHotel = new List<CPosHotel>();
                if (cmbHotelMethod.SelectedIndex == 0)
                {
                    if (cmbHotel.SelectedIndex == 0)
                        lstHotel = XML.Hotel_GetAllHotel();
                    else
                        lstHotel = XML.Hotel_GetHotelByDistrict(cmbHotel.Text);
                }
                else if (cmbHotelMethod.SelectedIndex == 1)
                    lstHotel = XML.Hotel_GetHotelByStreet(cmbHotel.Text.Trim().ToLower());
                else
                    lstHotel = XML.Hotel_GetHotelByName(cmbHotel.Text.Trim().ToLower());
                AddMarkerHotel(lstHotel);
                if(lstHotel.Count > 0)
                    GoTo(lstHotel[0].lat, lstHotel[0].lng, focuszoom);
            }
            else
            {
                List<CPosATM> lstATM = new List<CPosATM>();
                if (cmbATM.SelectedIndex == 0)
                    lstATM = XML.Bank_GetAllATM();
                else
                    lstATM = XML.Bank_GetATMByBank(cmbATM.Text.Trim().ToLower());

                if (txtAddress.Text.Trim() != "")
                    lstATM = lstATM.Where(c => c.address.ToLower().Contains(txtAddress.Text.Trim().ToLower())).ToList();

                AddMarkerATM(lstATM);
                if (lstATM.Count > 0)
                    GoTo(lstATM[0].lat, lstATM[0].lng, focuszoom);
            }
        }
        private void cmbHotelMethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbHotelMethod.SelectedIndex == 0)
            {
                cmbHotel.DropDownStyle = ComboBoxStyle.DropDownList;
                label1.Text = "District";
            }
            else if (cmbHotelMethod.SelectedIndex == 1)
            {
                cmbHotel.DropDownStyle = ComboBoxStyle.Simple;
                label1.Text = "Street";
            }
            else if (cmbHotelMethod.SelectedIndex == 2)
            {
                cmbHotel.DropDownStyle = ComboBoxStyle.Simple;
                label1.Text = "Hotel name";
            }
        }

        private void rBATM_CheckedChanged(object sender, EventArgs e)
        {
            label1.Text = "Street";
        }
        #endregion

        #region Invoke script
        private void AddMarkerATM(List<CPosATM> list)
        {
            foreach (CPosATM atm in list)
            {
                object[] args = new object[7];
                args[0] = atm.lat;
                args[1] = atm.lng;
                args[2] = false;
                args[3] = atm.place;
                args[4] = atm.address;
                args[5] = atm.workinghour;
                args[6] = atm.image;
                webBrowser_Map.Document.InvokeScript("AddMarker", args);
            }
        }

        private void AddMarkerHotel(List<CPosHotel> list)
        {
            foreach (CPosHotel hotel in list)
            {
                object[] args = new object[7];
                args[0] = hotel.lat;
                args[1] = hotel.lng;
                args[2] = true;
                args[3] = hotel.name;
                args[4] = hotel.address;
                args[5] = hotel.detail;
                args[6] = hotel.image;

                webBrowser_Map.Document.InvokeScript("AddMarker", args);
            }
        }

        private void GoTo(string lat, string lng, string zoom)
        {
            object[] args = new object[3];
            args[0] = lat;
            args[1] = lng;
            args[2] = zoom;

            webBrowser_Map.Document.InvokeScript("GoTo", args);
        }

        private void ClearMarker()
        {
            webBrowser_Map.Document.InvokeScript("ClearMarker");
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            if (lathotel == "" || lnghotel == "")
                return;
            List<CPosATM> lstketqua = GetPostATMaroundHotel();
            AddMarkerATM(lstketqua);
        }
    }
}
